package com.itheima.mynetty;

import com.itheima.mynetty.codec.ProtoStuffEncoder;
import com.itheima.mynetty.handler.client.ClientInboundHandler1;
import com.itheima.mynetty.handler.client.ClientWriteCheckIdleHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldPrepender;

public class NettyClient {

    public static void main(String[] args) {
        NettyClient client = new NettyClient();
        client.connect();
    }

    private void connect() {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new LengthFieldPrepender(4));
                        //String序列化
//                        pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
                        //protobuf序列化
//                        pipeline.addLast(new ProtobufEncoder());
                        //protostuff序列化
                        pipeline.addLast(new ProtoStuffEncoder());
                        //心跳消息
                        pipeline.addLast(new ClientWriteCheckIdleHandler());
                        pipeline.addLast(new ClientInboundHandler1());
                    }
                });

        try {
            ChannelFuture future = bootstrap.connect("127.0.0.1", 8888).sync();
//            Channel channel = future.channel();
//            ByteBuf buffer = channel.alloc().buffer();
//            buffer.writeBytes("Hello Server, I am Client".getBytes(CharsetUtil.UTF_8));
//            channel.writeAndFlush(buffer);

            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            group.shutdownGracefully();
        }
    }
}
